package com.yanx.system.web;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpUtil;
import com.yanx.common.command.executor.ExecutorHolder;
import com.yanx.common.exception.BusinessException;
import com.yanx.common.security.LoginInforRecordUtils;
import com.yanx.common.security.preauthorize.PreAuthorizeAspect;
import com.yanx.common.utils.Collect_;
import com.yanx.common.utils.Message_;
import com.yanx.common.utils.String_;
import com.yanx.system.base.model.dto.SysUserDto;
import com.yanx.system.base.model.vo.SysMenuVo;
import com.yanx.system.base.model.vo.SysUserVo;
import com.yanx.system.client.SystemRpc;
import com.yanx.system.client.dto.LoginUserVo;
import com.yanx.system.client.dto.MetaVo;
import com.yanx.system.client.dto.RouterVo;
import com.yanx.system.web.command.SystemUserAddCmd;
import com.yanx.system.web.infra.constant.UserConstants;
import com.yanx.system.web.query.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 系统RPC实现类
 *
 * @author gotanks
 * @create 2021-01-29 23:38
 **/

@DubboService(version = "1.0")
public class SystemRpcImpl extends ExecutorHolder implements SystemRpc {

    @Override
    public LoginUserVo getLoginUserByUsername(String username) {
        SysUserVo sysUserVo = queryExecutor.execute(new SysUserByUserNameQry(username));
        if (sysUserVo == null) {
            return null;
        }
        LoginUserVo loginUserVo = new LoginUserVo();// SysMapper.INSTANCE.toLoginUser(sysUser);
        loginUserVo.setUser(BeanUtil.beanToMap(sysUserVo));
        String status = sysUserVo.getStatus();
        if ("1".equals(status)) {
            loginUserVo.setDisabled(true);
        }
        if ("2".equals(status)) {
            loginUserVo.setLocked(true);
        }
        Long userId = sysUserVo.getId();
        if (userId != null && userId == 1) {
            loginUserVo.setRoles(Collect_.newHashSet(PreAuthorizeAspect.ALL_PERMISSION));
            loginUserVo.setPermissions(Collect_.newHashSet(PreAuthorizeAspect.ALL_PERMISSION));
        } else {
            loginUserVo.setRoles(queryExecutor.execute(new RoleKeysByUserIdQry(userId)));
            loginUserVo.setPermissions(queryExecutor.execute(new PremsByUserIdQry(userId)));
        }
        return loginUserVo;
    }

    @Override
    public List<RouterVo> getCurrentRouters() {
        List<SysMenuVo> menuVos = queryExecutor.execute(new SysMenuTreeByUserIdQry());
        return buildMenus(menuVos);
    }

    @Override
    public boolean captchaEnabled() {
        String captchaEnabled = queryExecutor.execute(new SysConfigByKeyQry("sys.account.captchaEnabled"));
        if (captchaEnabled == null) {
            return true;
        }
        return Convert.toBool(captchaEnabled);
    }

    @Override
    public boolean registerEnabled() {
        String registerUser = queryExecutor.execute(new SysConfigByKeyQry("sys.account.registerUser"));
        if (registerUser == null) {
            return true;
        }
        return Convert.toBool(registerUser);
    }

    @Override
    public void register(String username, String password) {
        //参数判断
        if (String_.isEmpty(username)) {
            throw new BusinessException("用户名不能为空");
        } else if (String_.isEmpty(password)) {
            throw new BusinessException("用户密码不能为空");
        } else if (username.length() < 2 || username.length() > 20) {
            throw new BusinessException("账户长度必须在2到20个字符之间");
        } else if (password.length() < 5 || password.length() > 20) {
            throw new BusinessException("密码长度必须在5到20个字符之间");
        }
        SysUserDto user = new SysUserDto();
        user.setUserName(username);
        user.setPassword(password);
        commandExecutor.execute(new SystemUserAddCmd(user));
        LoginInforRecordUtils.success(username, Message_.message("user.register.success"));
//        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
    }

    public List<RouterVo> buildMenus(List<SysMenuVo> menus) {
        List<RouterVo> routers = new LinkedList<>();
        for (SysMenuVo menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), String_.equals("1", menu.getIsCache()), menu.getPath()));
            List<SysMenuVo> cMenus = (List<SysMenuVo>) menu.getChildren();
            if (!cMenus.isEmpty() && cMenus.size() > 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache()), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenuVo menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenuVo menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenuVo menu) {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = UserConstants.INNER_LINK;
        } else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenuVo menu) {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(SysMenuVo menu) {
        return menu.getIsFrame().equals(UserConstants.NO_FRAME) && (HttpUtil.isHttp(menu.getPath()) || HttpUtil.isHttps(menu.getPath()));
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenuVo menu) {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    public String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path, new String[]{"http://", "https://", "www.", "."},
                new String[]{"", "", "", "/"});
    }
}
